<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {


    private $WB_OAUTH;
    private $WB_AKEY;
    private $WB_SKEY;
    private $WB_CALLBACK_URL;
    private $WB_UIDS;

    function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        include  LIBPATH.'/Weibo/SaeTOAuthV2.php' ;
        $this->WB_UIDS = array('5303874222','5217890053');
        $this->WB_AKEY = $this->config->item('WB_AKEY');
        $this->WB_SKEY = $this->config->item('WB_SKEY');
        $this->WB_CALLBACK_URL = $this->config->item('WB_CALLBACK_URL');
        $this->WB_OAUTH = new SaeTOAuthV2($this->WB_AKEY, $this->WB_SKEY);

     }

    public function WB_CLIENT($access_token = '')
    {
        if(!empty($access_token)){
            return new SaeTClientV2( $this->WB_AKEY, $this->WB_SKEY,$access_token);
        }
    }

    /**
     *
     * 登陆页面
     */
    function login()
    {
        //是否已经登陆
        $admin_user_id = $this->session->userdata('admin_user_id');
        if (!empty($admin_user_id)) redirect(site_url('admin/index'));
        $data['login_url'] = site_url('admin/index/tologin');
        $data['oauth_url'] = $code_url = $this->WB_OAUTH->getAuthorizeURL($this->WB_CALLBACK_URL);
        $this->load->view('user/login', $data);
    }


    public function callback()
    {
        $code = $this->input->get_post('code');

        if (isset($code))
        {
            $keys = array();
            $keys['code'] = $code;
            $keys['redirect_uri'] = $this->WB_CALLBACK_URL;
            try
            {
                $token = $this->WB_OAUTH->getAccessToken('code', $keys);
            }
            catch (OAuthException $e)
            {
            }
        }

        if ($token)
        {
            $this->session->set_userdata(array('wb_token'=>$token));

            /*$text = '点我至少有10元天猫红包哟，每天都可以领哟 ：  http://s.click.taobao.com/OcfsPPx';
            $this->upload($text,'http://tva4.sinaimg.cn/crop.324.78.460.460.180/7f6c3970gw1ekpxzvptl6j20sg0izn3c.jpg');*/


        }

    }

    /**
     * 发表微博
     */
    public function send($text = '')
    {
        if (empty($text)) return false;
        $token = $this->session->userdata('wb_token');
        if (!empty($token))
        {
            $ret = $this->WB_CLIENT($token['access_token'])->update($text);    //发送微博
            if (isset($ret['error_code']) && $ret['error_code'] > 0)
            {
                return "<p>发送失败，错误：{$ret['error_code']}:{$ret['error']}</p>";
            }
            else
            {
                return true;
            }
        }
    }

    /**
     * 发表图片微博
     */
    public function upload($text = '', $pic_path = '')
    {
        if (empty($text) || empty($pic_path)) return false;
        $token = $this->session->userdata('wb_token');
        if (!empty($token))
        {
            $ret = $this->WB_CLIENT($token['access_token'])->upload($text, $pic_path);    //发送微博
            if (isset($ret['error_code']) && $ret['error_code'] > 0)
            {
                return "<p>发送失败，错误：{$ret['error_code']}:{$ret['error']}</p>";
            }
            else
            {
                return true;
            }
        }
    }


    public function get_latest()
    {
        $token = $this->session->userdata('wb_token');
        if (!empty($token))
        {
            $list = $this->WB_CLIENT($token['access_token'])->home_timeline(1,200);
        }

        $data =  array();
        if($list['statuses'])
        {
            foreach ($list['statuses'] as $index => $statuse)
            {
                if(isset($statuse['retweeted_status'])|| empty($statuse['pic_urls'])) continue; // 过滤转发的微博

                if(!in_array($statuse['user']['id'],$this->WB_UIDS)){
                    continue; // 过滤掉非优惠券用户
                }
                $image = isset($statuse['bmiddle_pic']) ? $statuse['bmiddle_pic'] : $statuse['original_pic'] ;
                $data[$index]['id'] = $statuse['id'] ;
                $data[$index]['user_id'] = $statuse['user']['id'];
                $data[$index]['user_nickname'] = $statuse['user']['name'];
                $data[$index]['text'] = $statuse['text'] ;
                $data[$index]['image'] = $image ;
                $data[$index]['created_at'] = $statuse['created_at'] ;
            }
        }

        print_r($data); //4.0392153631564E+15
    }


    public function do_send()
    {
        /** Include PHPExcel */
        require_once(APPPATH.'libraries/Classes/PHPExcel/IOFactory.php');
        $file = getcwd().DIRECTORY_SEPARATOR.'static\code.xlsx';

        if ( ! file_exists($file))
        {
            $this->error('file not found','',true);
        }


        $reader = PHPExcel_IOFactory::createReader('Excel2007'); //设置以Excel5格式(Excel97-2003工作簿)

        $PHPExcel = $reader->load($file); // 载入excel文件
        $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表

        $highestRow = $sheet->getHighestRow(); // 取得总行数

        $highestColumm = $sheet->getHighestColumn(); // 取得总列数

        $child_num = 0 ;
        $data = array();
        for ($row = 2; $row <= $highestRow; $row++) //行数是以第1行开始
        {
            $data[$row]['name'] = $sheet->getCell('B' . $row)->getValue() ;
            $data[$row]['price'] = $sheet->getCell('G' . $row)->getValue() ;
            $data[$row]['image'] = $sheet->getCell('C' . $row)->getValue() ;
            $data[$row]['url'] = $sheet->getCell('V' . $row)->getValue() ;
            $data[$row]['desc'] = $sheet->getCell('R' . $row)->getValue() ;
        }


        foreach ($data as $index => $item)
        {
            $text = $item['name'].'【'.$item['price'].'】'."\n".$item['desc'].$item['url'];
            $this->upload($text, $item['image']);
            break;
        }

    }
}